package cn.fastoo.web.backstage.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.alibaba.fastjson.JSON;
import org.springframework.data.domain.Page;

/**
 * jQuery-EasyUI:DataGrid数据表格工具类
 * 
 * @author lowkey
 *
 */
public abstract class DataGridUtils {
	/**
	 * Page转换为DataGrid数据格式json字符串
	 * 
	 * @param page
	 * @return
	 */
	public static <T> String PageToJson(Page<T> page) {
		long total = page.getTotalElements();
		List<T> list = page.getContent();
		String json = "";
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("total", total);
			map.put("rows", list);
			// ObjectMapper mapper = new ObjectMapper();
			// json = mapper.writeValueAsString(map);
			json = JSON.toJSONString(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toString();
	}

	/**
	 * 自定义page转换为json
	 * 
	 * @param com
	 *            .hko.base.Page<T> page
	 * @return
	 */
	public static <T> String PageToJson2(cn.fastoo.web.backstage.Page<T> page) {

		long total = page.getTotalItems();
		List<T> list = page.getResult();
		String json = "";
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("total", total);
			map.put("rows", list);
			// ObjectMapper mapper = new ObjectMapper();
			// json = mapper.writeValueAsString(map);
			json = JSON.toJSONString(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toString();
	}

	/**
	 * List转换为DataGrid数据格式json字符串
	 * 
	 * @param list
	 * @return
	 */
	public static <T> String ListToJson(List<T> list) {
		String json = "";
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("total", list.size());
			map.put("rows", list);
			// ObjectMapper mapper = new ObjectMapper();
			// json = mapper.writeValueAsString(map);
			json = JSON.toJSONString(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toString();
	}
}
